
import React, { useState, useEffect } from 'react';
import { Button, Table, Input, Space, Select, Modal, Form, message, DatePicker } from 'antd';
import type { TableColumnsType } from 'antd';
// import { SearchOutlined } from '@ant-design/icons';
import styles from './index.less';
import { getBuy, getBuyers, getStorers, deleteBuy, distributionBuy, getCompany, inMaterialRequire } from '@/api/services';
import AddBuyModal from './components/AddBuyModal';

const OrderMangement: React.FC = () => {
    const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
    const [data, setData] = useState([]);
    const [page, setPage] = useState<number>(1);
    const [total, setTotal] = useState(0);
    const [buyers, setBuyers] = useState<any>([]);//采购员
    const [storers, setStorers] = useState<any>([]);//仓库管理员
    const [modalOpen, setModalOpen] = useState<boolean>(false);
    const [storerId, setStorerId] = useState<any>('');
    const [buyerId, setBuyerId] = useState<any>('');


    const getBuyList = () => {
        getBuy({
            page: page,
            size: 5,
            buyerId: buyerId ? buyerId : '',
            storerId: storerId ? storerId : '',
        }).then((res: any) => {
            if (res.status == 200) {
                console.log(res);
                setData(res.results);
                setTotal(res.length);
            }
        });
    }

    useEffect(() => {
        getBuyList();
    }, [page, storerId, buyerId]);

    const handleSelectChange = (id: any, value: any) => {
        distributionBuy({
            buyId: id,
            buyerId: value
        }).then((res: any) => {
            if (res.status == 200) {
                console.log(res);
                getBuyList();
            }

        })
    }

    const handleChange = (pagination: any, filters: any, sorter: any) => {
        console.log(filters);
        const customerCompany = filters.storerName ? filters.storerName[0] : '';
        setStorerId(customerCompany);
        const plannerName = filters.buyerName ? filters.buyerName[0] : '';
        setBuyerId(plannerName);
    };

    //原料入库
    const inWareHouse = (id: any, detail: any) => {
        inMaterialRequire({
            buyId: id,
            detail: detail
        }).then((res: any) => {
            if (res.status == 200) {
                message.success(res.msg);
                getBuyList();
            }
        })
    }

    const hasSelected = selectedRowKeys.length > 0;

    //采购员列表
    useEffect(() => {
        getBuyers().then((res: any) => {
            if (res.status == 200) {
                console.log(res);
                const options = res.results.map((user: any) => ({
                    value: user.user_id,
                    label: user.user_name,
                }));
                setBuyers(options);
            }

        })
    }, [])

    //仓库管理员列表
    useEffect(() => {
        getStorers().then((res: any) => {
            if (res.status == 200) {
                console.log(res);
                const options = res.results.map((user: any) => ({
                    value: user.user_id,
                    label: user.user_name,
                }));
                setStorers(options);
            }

        })
    }, [])



    //删除订单
    const delBuyList = (id: any) => {
        console.log('id', id);
        deleteBuy({
            buyId: id
        }).then((res: any) => {
            if (res.status == 200) {
                // console.log(res);
                message.success('删除成功');
                getBuyList();
            }
        })
    }


    const handleAddCancel = () => {
        setModalOpen(false);
    }

    const formatDetail = (data: any) => {
        var dataArray = data.split("||");
        var result = "";

        // 遍历数组中的每一对数据
        for (var i = 0; i < dataArray.length; i += 2) {
            // 获取物品名称和数量
            var item = dataArray[i].trim();
            var quantity = dataArray[i + 1].trim();

            // 格式化为键值对的形式，并添加到结果中
            result += item + "：" + quantity;

            // 如果不是最后一对数据，添加逗号分隔符
            if (i < dataArray.length - 2) {
                result += ", ";
            }
        }

        return result;
    }

    const paginationConfig = {
        total: total,
        onChange: (page: number, pageSize?: number) => {
            setPage(page);
        },
        showTotal: (total: number, range: [number, number]) => `共 ${total} 条数据`,
    }
    const columns = [
        {
            title: '采购明细',
            width: 150,
            dataIndex: 'buy_detail',
            render: (_: any, record: any) => (
                <div>
                    <Space direction="vertical" size="middle" style={{ display: 'flex' }}>
                        {record.buy_detail && formatDetail(record.buy_detail).split(',').map((item: any, index: number) => (
                            <span key={index}>{item}</span>
                        ))}
                    </Space>
                </div>
            )
        },
        {
            title: '采购提交时间',
            dataIndex: 'buy_posttime',
        },
        {
            title: '采购完成截止时间',
            dataIndex: 'buy_deadline',
        },
        {
            title: '采购状态',
            dataIndex: 'buy_type'
        },
        {
            title: '采购金额',
            dataIndex: 'buy_money'
        },
        {
            title: '采购员',
            dataIndex: 'buyerName',
            filters: buyers.map((buyer: any) => ({
                value: buyer.value,
                text: buyer.label
            })),
            render: (_: any, record: any) => (
                <Select
                    style={{ width: 120 }}
                    onChange={(value) => handleSelectChange(record.buy_id, value)}
                    value={record.buyerName}
                    options={buyers}
                />
            )
        },
        {
            title: '仓库管理员',
            dataIndex: 'storerName',
            filters: storers.map((buyer: any) => ({
                value: buyer.value,
                text: buyer.label
            })),
        },
        {
            title: 'Action',
            dataIndex: '',
            key: 'x',
            render: (_: any, record: any) =>
                <Space size="middle">
                    {
                        record.buy_detail == null ?
                            <a
                                onClick={() => message.info('原料还未采购完成')}
                            >原料入库</a> :
                            <a
                                onClick={() => inWareHouse(record.buy_id, record.buy_detail)}
                            >原料入库</a>
                    }

                    <a onClick={() => delBuyList(record.buy_id)}>删除</a>
                </Space>
        },
    ];


    return (
        <div className={styles.orderContainer}>

            <div className={styles.header}>

                <Button type="primary" style={{ marginRight: 20 }}
                    onClick={() => {
                        setModalOpen(true);
                        // getProductList();
                        // form.resetFields();
                        // sessionStorage.removeItem('buy_id');
                    }}
                >新增采购订单</Button>
                {/* <Button type="primary" danger>批量删除</Button> */}
            </div>
            <Table 
                onChange={handleChange}
                columns={columns} dataSource={data}
                pagination={paginationConfig} />
            {modalOpen && <AddBuyModal onCancel={handleAddCancel} getBuyList={getBuyList}/>}

        </div>
    );
};

export default OrderMangement;